#include "qLagerwidgetProdavnica.h"
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>
#include <QDesktopWidget>
#include "chelperclass.h"

QLagerProdavnicaWidget::QLagerProdavnicaWidget(QWidget *parent)
	: QMyBaseFormWidget(parent)
    ,m_selectedText("") 
    ,m_selectedTextName("")
{
	ui.setupUi(this);
	QDesktopWidget desk;
	QRect deskRect = desk.screenGeometry();
	ui.layoutWidget->setFixedWidth(deskRect.width() - 300);
	ui.layoutWidget->setFixedHeight(deskRect.height()-200);
    ui.tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui.tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui.tableView->setSortingEnabled(true);
	connect(ui.tableView->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView, SLOT(sortByColumn(int)));
    lista("%%%");
}

QLagerProdavnicaWidget::~QLagerProdavnicaWidget()
{

}

void QLagerProdavnicaWidget::radioButtonClicked()
{
    lista(ui.lineEdit->text());
}

void QLagerProdavnicaWidget::pressEscape()
{
    emit closeW();
}


void QLagerProdavnicaWidget::lista(const QString& nameSearch)
{
    if (nameSearch.count() < 2)
    {
        return;
    }

    QLocale loc;
    int mag_id = 1;
	QString tempLimit = "";
    int r = 0;
    int c = 7;
    int fieldNo[7];
    QString country[7];
    int colWidth[] = {50, 250, 80, 180, 90, 90, 90};
    QString colName[7] = {"id", "artikal", "edm", "proizvoditel", "sum(vkol)", "sum(ikol)", "sum(vkol)-sum(ikol)"};

    QString temp = "";
    temp = "select distinct artikli.id, artikli.artikal, artikli.edm, artikli.proizvoditel, artikli.id "
    "from magacin_prodavnica "
    "left join artikli on  magacin_prodavnica.artikal_id = artikli.id "
    "where artikli.artikal like '%" + nameSearch + "'";
    QSqlQuery query(temp);
    QSqlError err = query.lastError();
    model = new QStandardItemModel(r, c);
    model->setHeaderData( 0, Qt::Horizontal, trUtf8("Ид"));
    model->setHeaderData( 1, Qt::Horizontal, trUtf8("Артикал"));
    model->setHeaderData( 2, Qt::Horizontal, trUtf8("Едм"));
	model->setHeaderData( 3, Qt::Horizontal, trUtf8("Производител"));

	model->setHeaderData( 4, Qt::Horizontal, trUtf8("Влез. Кол."));
	model->setHeaderData( 5, Qt::Horizontal, trUtf8("Изл. Кол."));
	model->setHeaderData( 6, Qt::Horizontal, trUtf8("Салдо"));
    ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);

    ui.tableView->setHorizontalHeader(header);
    header->show();
    int row = 0;
	CHelperClass chc(this);
	float vkVlezKol = 0.f;
	float vkIzlezKol = 0.f;
	float vkSaldo = 0.f;
	setUpdatesEnabled(false);
	chc.createSaldoMapAll_Prodavnica();
    while (query.next()) 
    {
        for (int i = 0; i < c; i++)
        {
            QString temp = query.value(i).toString();
            QStandardItem *item = NULL; 
				
			if (i == 4)
			{
				vkVlezKol = chc.getLagerListaAll_Prodavnica(query.value(4).toString() , (QString)"PRILIV");
				temp =  loc.toString(vkVlezKol ,'f', 2);
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignRight);
			}
			else if (i == 5)
			{
				vkIzlezKol = chc.getLagerListaAll_Prodavnica(query.value(4).toString() , (QString)"ODLIV");
				temp =  loc.toString(vkIzlezKol ,'f', 2);
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignRight);
			}
			else if (i == 6)
			{
				vkSaldo = vkVlezKol - vkIzlezKol;
				temp =  loc.toString(vkSaldo ,'f',2);
				item = new QStandardItem(temp);
				QBrush newBrush;
				if (vkSaldo < 0)
				{
					newBrush.setColor(Qt::darkRed);
					item->setForeground(newBrush);
				}
				else if (vkSaldo == 0)
				{
					newBrush.setColor(Qt::black);
					item->setForeground(newBrush);
				}
				else
				{
					newBrush.setColor(Qt::darkGreen);
					item->setForeground(newBrush);
				}
				item->setTextAlignment(Qt::AlignRight);
			}
            else
            {
                item = new QStandardItem(temp);
                item->setTextAlignment(Qt::AlignLeft);
            }
            item->setEditable(false);
            ui.tableView->setRowHeight(row, 18);
            ui.tableView->setColumnWidth(i, colWidth[i]);
            model->setItem(row, i, item);
        }
		row++;
    } 
	setUpdatesEnabled(true);

    QItemSelectionModel *sm = ui.tableView->selectionModel();
    connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
        this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
    ui.tableView->show();
}

void QLagerProdavnicaWidget::on_lineEdit_textChanged(const QString &)
{
	lista(ui.lineEdit->text());
}


void QLagerProdavnicaWidget::on_tableView_clicked(const QModelIndex &modelX)
{
	int i = modelX.row();
	m_selectedText = model->item(i, 0) ? model->item(i, 0)->text():"";
}

void QLagerProdavnicaWidget::setFocusSearchField()
{
	ui.lineEdit->setFocus();
}


void QLagerProdavnicaWidget::pressReturn()
{
    if (ui.lineEdit->hasFocus())
    {
        ui.tableView->setFocus();
    }
    else if (ui.tableView->hasFocus())
	{
		QString magTip =  "1";
        emit sLagerProdavnicaToDokument(m_selectedText, m_selectedTextName, m_selectedTextNameSaldo, magTip);	
	}

}

void QLagerProdavnicaWidget::setInitText(QString text)
{
	ui.lineEdit->setText(text);
	ui.lineEdit->selectAll();
	ui.lineEdit->setFocus();
}

void QLagerProdavnicaWidget::selectionChanged(QModelIndex modelX, QModelIndex modelY)
{
    int i = modelX.row();
    m_selectedText = model->item(i, 0) ? model->item(i, 0)->text():"";
    m_selectedTextName = model->item(i, 1) ? model->item(i, 1)->text():"";
    m_selectedTextNameSaldo = model->item(i, 5) ? model->item(i, 5)->text():"";
	lista_detail(m_selectedText);
}

void QLagerProdavnicaWidget::lista_detail(const QString& nameSearch)
{
	QLocale loc;
	if (nameSearch.length() < 0)
	{
		ui.tableView_2->hide();
		return;
	}

	int r = 0;
	int c = 6;
	int colWidth[] = {0, 0, 200, 100, 100, 100};
	QString colName[] = {"id", "sifra", "artikal", "edm", "ikol", "icena", "mag_id"};
	QString temp = 
		" SELECT magacin.artikal_id, prodavnica_id, komintenti.naziv, 0, 0, 0 "
		" FROM dokumenti_prodavnica dokumenti "
		" LEFT JOIN magacin_prodavnica magacin ON (dokumenti.dok_id = magacin.dok_id  AND dokumenti.dok_tip = magacin.dok_tip ) "
		" LEFT JOIN komintenti ON dokumenti.prodavnica_id = komintenti.id "
		" WHERE artikal_id = " + m_selectedText + 
		" GROUP BY magacin.artikal_id, prodavnica_id ";
	QSqlQuery query(temp);
	model2 = new QStandardItemModel(r,c);
	model2->setHeaderData( 0, Qt::Horizontal, trUtf8("Артикал-Ид."));
	model2->setHeaderData( 1, Qt::Horizontal, trUtf8("Продавница-Ид."));
	model2->setHeaderData( 2, Qt::Horizontal, trUtf8("Продавница"));
	model2->setHeaderData( 3, Qt::Horizontal, trUtf8("Прилив"));
	model2->setHeaderData( 4, Qt::Horizontal, trUtf8("Одлив"));
	model2->setHeaderData( 5, Qt::Horizontal, trUtf8("Салдо"));

	ui.tableView_2->setModel(model2);
	header2 = new QHeaderView(Qt::Horizontal, this);
	header2->setClickable(true);
	ui.tableView_2->setHorizontalHeader(header2);
	header2->show();
	int row = 0;
	float vkVlezKol = 0.f;
	float vkIzlezKol = 0.f;
	float vkSaldo = 0.f;
	CHelperClass chc(this);
	setUpdatesEnabled(false);
	chc.createSaldoMapAll_ProdavnicaByArtikal(m_selectedText);

	while (query.next()) 
	{
		for (int i = 0; i < c; i++)
		{
			QString temp = query.value(i).toString();
			QStandardItem *item = NULL; 

			if (i == 3)
			{
				vkVlezKol = chc.getLagerListaAll_ProdavnicaArtikal(query.value(1).toString() , (QString)"PRILIV");
				temp =  loc.toString(vkVlezKol ,'f', 2);
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignRight);
			}
			else if (i == 4)
			{
				vkIzlezKol = chc.getLagerListaAll_ProdavnicaArtikal(query.value(1).toString() , (QString)"ODLIV");
				temp =  loc.toString(vkIzlezKol ,'f', 2);
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignRight);
			}
			else if (i == 5)
			{
				vkSaldo = vkVlezKol - vkIzlezKol;
				temp =  loc.toString(vkSaldo ,'f',2);
				item = new QStandardItem(temp);
				QBrush newBrush;
				if (vkSaldo < 0)
				{
					newBrush.setColor(Qt::darkRed);
					item->setForeground(newBrush);
				}
				else if (vkSaldo == 0)
				{
					newBrush.setColor(Qt::black);
					item->setForeground(newBrush);
				}
				else
				{
					newBrush.setColor(Qt::darkGreen);
					item->setForeground(newBrush);
				}
				item->setTextAlignment(Qt::AlignRight);
			}
			else
			{
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignLeft);
			}
			item->setEditable(false);
			ui.tableView_2->setRowHeight(row, 18);
			ui.tableView_2->setColumnWidth(i, colWidth[i]);
			model2->setItem(row, i, item);
		}
		row++;
	} 
	setUpdatesEnabled(true);
	ui.tableView_2->show();
}
